//
//  SearchViewController.m
//  sdk2.0zhengquandasha
//
//  Created by peng on 15/11/30.
//  Copyright © 2015年 palmaplus. All rights reserved.
//

#import "SearchViewController.h"
#import <Nagrand/NGROverlayer.h>
#import <Nagrand/Nagrand.h>
#import "HistorySearchBar.h"
#import "searchView.h"
#import "NGRDataSourceModel.h"

#define kScreenHeight   [[UIScreen mainScreen] bounds].size.height
#define kScreenWidth    [[UIScreen mainScreen] bounds].size.width
@interface SearchViewController ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate,NGRDataSourceDelegate>
{
    NGRDataSource *_dataSource;
}
//@property(nonatomic,strong) UISearchBar* searchBar;
@property(nonatomic,strong) UITableView* searchResultTableView;
@property(nonatomic,strong) NSMutableArray *hisyArray;
//@property(nonatomic,strong)HistorySearchBar *searchBar;
@property (nonatomic,strong)UISearchBar *searchBar;
@property(nonatomic,strong)searchView *searchView;
/** 搜索提醒 */
@property (nonatomic,strong)UITableView *tableView;
/** tableview的数据源 */
@property (nonatomic,strong)NSArray *dataSourceArr;
@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     self.view.backgroundColor = [UIColor whiteColor];
    [self createNGRDataSourceModel];
    [self addNavigationSearchBar];
    [self addSearchView];
    _dataSource = [[NGRDataSource alloc]init];
    _dataSource.delegate = self;
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, KWIDTH, KHEIGHT/2) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.hidden = YES;
    [self.view addSubview:self.tableView];
}

-(void)addSearchView{
        self.searchView = [[searchView alloc]initWithFrame:CGRectMake(0, 64, KWIDTH, KHEIGHT)];
    self.searchView.hotArr = [NSMutableArray arrayWithObjects:@"冯建",@"刘鹏",@"彭亚威",@"张竹君",@"刘品",@"徐远泰",@"徐曼鹭",@"张亚飞", nil];
//    self.search.historyArr = [NSMutableArray arrayWithObjects:@"冯建",@"冯建", nil];
    self.searchView.historyArr = [[NSUserDefaults standardUserDefaults] objectForKey:@"search"];
    [self.view addSubview:self.searchView];
    __weak typeof(self)weakSelf = self;
    self.searchView.searchBlock = ^(NSString *keyWords){
        //开始搜索
        if (weakSelf.poiSearchBlock) {
            weakSelf.poiSearchBlock(keyWords);
        }
    };
    self.searchView.deleteBlock = ^(){
        //清空历史记录
        NSMutableArray *arr = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"search"]];
        if(arr &&arr.count > 0){
        [arr removeAllObjects];
        }
        [[NSUserDefaults standardUserDefaults] setObject:arr forKey:@"search"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        weakSelf.searchView.historyArr = [[NSUserDefaults standardUserDefaults]objectForKey:@"search"];
        weakSelf.searchView.deleteBtn.hidden = YES;
        weakSelf.searchView.emptyHistoryLab.hidden = NO;
    };
}


-(void)addNavigationSearchBar{
//        UIButton* rightbutton = [UIButton buttonWithType:UIButtonTypeCustom];
//        [rightbutton addTarget:self action:@selector(searchTarget) forControlEvents:UIControlEventTouchUpInside];
//        rightbutton.frame = CGRectMake(0, 0, 20, 20);
//        [rightbutton setBackgroundImage:[UIImage imageNamed:@"Search_181px_1190971_easyicon.net"] forState:UIControlStateNormal];
    
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(40, 8, kScreenWidth - 120, 30)];
    _searchBar.backgroundColor = [UIColor clearColor];

    _searchBar.placeholder = @"输入目的地名称";
    _searchBar.delegate = self;
//    self.navigationItem.titleView = _searchBar;
    [self.navigationController.navigationBar addSubview:_searchBar];
    UIButton* rightbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightbutton setTitle:@"取消" forState:UIControlStateNormal];
    rightbutton.frame = CGRectMake(0, 0, 20, 20);
    rightbutton.width = 60;
    [rightbutton addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarbutton = [[UIBarButtonItem alloc]initWithCustomView:rightbutton];
    self.navigationItem.rightBarButtonItem = rightBarbutton;
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"ico_back"] forState:UIControlStateNormal];
    leftBtn.frame = CGRectMake(0, 0, 10, 20);
    [leftBtn addTarget:self action:@selector(leftAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarBtn = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBarBtn;
}

#pragma mark- 点击取消按钮
-(void)cancelAction{
    [_searchBar resignFirstResponder];
    self.tableView.hidden = YES;
    UIView *image = [self.view viewWithTag:1000];
    [image removeFromSuperview];
    if (!image) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)leftAction{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)searchBarResignFirstResponder{
    [self.searchBar resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark- 搜索的代理

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
        [self startSearchKeyWords];
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if (![searchBar.text isEqualToString:@""]) {
        [self searchKeyWord:searchBar.text];
            if (self.dataSourceArr) {
                self.tableView.hidden = NO;
                [self.tableView reloadData];
                return;
            }else{
                self.tableView.hidden = YES;
            }
    }else{
        self.tableView.hidden = YES;
    }
}

#pragma mark- 开始搜索关键字
-(void)startSearchKeyWords{
    [SVProgressHUD showWithStatus:@"玩命搜索中..."];
    [self.searchBar resignFirstResponder];
    self.poiSearchBlock(self.searchBar.text);
    NSMutableArray *arrSearch = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"search"]];
    if (!arrSearch) {
        arrSearch = [[NSMutableArray alloc]init];
        [arrSearch addObject:self.searchBar.text];
        [[NSUserDefaults standardUserDefaults] setObject:arrSearch forKey:@"search"];
    }else{
        int i = 0;
        for (NSString *str in arrSearch) {
            i++;
            if ([str isEqualToString:self.searchBar.text]) {
                return;
            }else{
                if (i == arrSearch.count) {
                    [arrSearch addObject:self.searchBar.text];
                    [[NSUserDefaults standardUserDefaults] setObject:arrSearch forKey:@"search"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
            }
        }
        if (arrSearch.count == 0) {
            [arrSearch addObject:self.searchBar.text];
            [[NSUserDefaults standardUserDefaults] setObject:arrSearch forKey:@"search"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        
    }
    
    self.searchView.historyArr = [[NSUserDefaults standardUserDefaults] objectForKey:@"search"];
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{

}
#pragma mark- UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.dataSourceArr) {
        return self.dataSourceArr.count;
    }else {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"CellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    cell.textLabel.text = self.dataSourceArr[indexPath.row];
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.searchBar.text = self.dataSourceArr[indexPath.row];
    [self startSearchKeyWords];
    self.tableView.hidden = YES;
}


-(void)viewWillDisappear:(BOOL)animated{
    [self.searchBar resignFirstResponder];
    self.searchBar.hidden = YES;
}
-(void)viewWillAppear:(BOOL)animated{
    self.searchBar.hidden = NO;
}

#pragma mark- NGRDataSourceModel

-(void)createNGRDataSourceModel{
    NGRDataSourceModel *data = [NGRDataSourceModel shareDataSourceModel];
    [data searchAllPoiWithFloorId:1672];
}

-(void)searchKeyWord:(NSString *)keyWord{
    self.dataSourceArr = [[NGRDataSourceModel shareDataSourceModel] selectTable:keyWord];
}

-(void)dealloc{
    
}
@end
